<!--
 * 档案案卷 tree组件
 * :
 * @version: 1.0
 * @author: lakeside hubin_yuan.410@hotmail.com
 * @date: 20120-07-14
 * @LastEditors:
 * @LastEditTime:
 -->
<template>
  <div class="tree_wrapper">
    <el-row class="tree_toolbar" justify="space-between" type="flex">
      <el-button-group>
        <el-button icon="el-icon-refresh" type="primary" @click="initializeRefresh">刷新</el-button>
        <el-button v-if="viewMode=='manage'" v-hasPermission="'dossier:archive:add'" icon="el-icon-circle-plus-outline" type="primary"
                   @click="nodeCreate">添加
        </el-button>
        <el-button icon="el-icon-s-help" @click="nodeUnchecked">取消选择</el-button>
        <el-button icon="el-icon-search" type="primary" @click="searchMode(true)">高级搜索</el-button>
      </el-button-group>
    </el-row>
    <el-row class="tree_content">
      <el-col :lg="layoutMode=='treeForm'?6:24" :md="layoutMode=='treeForm'?8:24" :span="layoutMode=='treeForm'?8:24"
              class="flex_column_wrapper">
        <el-input v-model="tree.filter" class="flex_column_header" clearable placeholder="输入关键字进行过滤"></el-input>
        <el-tree ref="dossierArchiveTree" :accordion="true" :data="tree.nodes" :draggable="viewMode=='manage'" :expand-on-click-node="false"
                 :filter-node-method="nodeFilter" :props="tree.props"
                 class="flex_column_content" default-expand-all highlight-current
                 node-key="id" @node-drop="nodeDropHandle" @node-click="nodeClickHandle">
                    <span slot-scope="{ node, data }" class="tree_node_toolbar">
                        <span>{{ node.label }}
                             <span v-for="(span,i) in tree.props.tags">
                                <span class="span_tag">{{ data[span] }}</span>
                             </span>
                        </span>
                        <span v-if="viewMode=='manage'">
                            <el-button v-if="layoutMode=='treeDialog'" v-hasPermission="'dossier:archive:edit'" type="text"
                                       @click="nodeModify(node, data)"> 编辑 </el-button>
                            <el-button v-hasPermission="'dossier:archive:del'" type="text"
                                       @click="nodeDelete(node, data)"> 删除</el-button>
                        </span>
                    </span>
        </el-tree>
      </el-col>
      <el-col v-if="layoutMode=='treeForm'&&viewMode=='manage'" :lg="18" :md="16" :span="16" class="p-1">
        <el-row class="p-1">
          <dossierArchiveForm ref="dossierArchiveForm" v-model="form"></dossierArchiveForm>
        </el-row>
        <el-row justify="center" type="flex">
          <el-button v-if="!form.editable&&form.entry.id" v-hasPermission="'dossier:archive:edit'" type="primary"
                     @click="formMode(true,'编辑',true)">编辑
          </el-button>
          <el-button v-if="form.editable" @click="formMode(true,'详情',false,tree.entry.data)">取 消</el-button>
          <el-button v-if="form.editable" type="primary" @click="formSubmit">保存</el-button>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog v-if="layoutMode=='treeDialog'&&viewMode=='manage'" v-dialogDrag :title="form.title" :visible.sync="form.visible"
               top="5vh" width="80%">
      <dossierArchiveForm ref="dossierArchiveForm" v-model="form"></dossierArchiveForm>
      <span slot="footer" class="dialog-footer">
                <el-button v-if="!form.editable" v-hasPermission="'dossier:archive:edit'" type="text"
                           @click="formMode(true,'编辑',true)">编辑</el-button>
                <el-button v-if="!form.editable" @click="formMode(false)">关闭</el-button>
                <el-button v-if="form.editable" @click="formMode(false)">取 消</el-button>
                <el-button v-if="form.editable" type="primary" @click="formSubmit">保存</el-button>
           </span>
    </el-dialog>
    <el-dialog v-dialogDrag :visible.sync="search.visible" title="高级搜索" top="5vh" width="80%">
      <dossierArchiveSearch ref="dossierArchiveSearch" v-model="search"></dossierArchiveSearch>
      <span slot="footer" class="dialog-footer">
                <el-button @click="searchMode(false)">取 消</el-button>
                <el-button @click="searchReset(true)">重置</el-button>
                <el-button type="primary" @click="searchSubmit">搜索</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import *  as dossierArchiveApi from '../apis/archive'
import {api_mixin, form_mixin, search_mixin, tree_mixin} from "@/mixins";
import DossierArchiveForm from "./components/form"
import DossierArchiveSearch from "./components/search"

export default {
  name: "dossierArchiveTree",
  props: {
    viewMode: {type: String, default: "manage"},
    layoutMode: {type: String, default: "treeForm"}
  },
  components: {DossierArchiveSearch, DossierArchiveForm},
  mixins: [api_mixin, form_mixin, search_mixin, tree_mixin],
  data() {
    return {
      tree: {
        props: {
          children: "children",
          label: "name",
          tags: ["modelName", "validStatusName"],
          level: "level",
          layerName: "layerName",
          /*layerCode:"layerCode",
          parentCode:"parentCode",*/
          value: "id",
          sort: "sortNum",
          parent: "parentId"
        },
      }
    }
  },
  computed: {
    treeFilter() {
      return this.tree.filter
    }
  },
  watch: {
    'tree.filter': {
      handler(value) {
        this.$refs.dossierArchiveTree.filter(value)
      }
    },
    "form.entry.name": {
      handler(value) {
        if (this.form.editable) {
          if (this.form.entry[this.tree.props.parent]) {
            let parentNode = this.$refs.dossierArchiveTree.getNode(this.form.entry[this.tree.props.parent])
            this.adjustFormLayerData(parentNode)
          } else {
            this.form.entry[this.tree.props.layerName] = this.form.entry[this.tree.props.label]
            this.form.entry[this.tree.props.level] = 0
          }
        }
      }
    },
    /*"form.entry.code": {
        handler(value) {
            if(this.form.editable) {
                if(this.form.entry[this.tree.props.parent]){
                   let parentNode= this.$refs.dossierArchiveTree.getNode(this.form.entry[this.tree.props.parent])
                     this.adjustFormLayerData(parentNode)
                }
            }
        }
    }*/
  },
  activated() {
    if (this.$route.meta.keep.state) {
      this.keepStateRefresh()
    } else {
      this.initializeRefresh()
    }
  },
  created() {
    this.treeLoadRefresh()
  },
  methods: {
    /**tree节点取消选择*/
    nodeUnchecked() {
      this.$refs.dossierArchiveTree.setCurrentKey(null)
      this.tree.entry = {}
      if (this.layoutMode == 'treeForm') {
        this.formMode(true, '详情', false, {})
      }
      this.$emit('choiceChange', '', {})
    },
    /** 动态调整表单层级数据 */
    adjustFormLayerData(treeNode, hasParent = false) {
      if (hasParent) {
        treeNode = treeNode.parent
      }
      let nodeEntry = treeNode.data
      let nodeLevel = treeNode.level

      //this.form.entry[this.tree.props.parent] = nodeEntry[this.tree.props.value] || ''
      this.form.entry[this.tree.props.level] = nodeEntry[this.tree.props.level] + 1
      this.form.entry[this.tree.props.layerName] =
          (nodeLevel > 0 ? nodeEntry[this.tree.props.layerName] + ">" : "") +
          (this.form.entry[this.tree.props.label] ? this.form.entry[this.tree.props.label] : "")
      /* this.form.entry[this.tree.props.layerCode] =
               (nodeLevel > 0 ? nodeEntry[this.tree.props.layerCode] : "") +
               (this.form.entry[this.tree.props.code] ? this.form.entry[this.tree.props.code] : "")
       this.form.entry[this.tree.props.parentCode] =
               (nodeLevel > 0 ? nodeEntry[this.tree.props.layerCode] : "")*/
    },

    /**tree节点拖拽*/
    nodeDropHandle(draggingNode, dropNode, dropType) {
      let srcEntry = draggingNode.data
      let tagEntry = dropNode.data
      let parentEntry = dropNode.parent.data
      let parentNodeLevel = dropNode.parent.level
      let hasUpdate = false
      switch (dropType) {
        case "inner":
          srcEntry[this.tree.props.parent] = tagEntry[this.tree.props.value] || ''
          srcEntry[this.tree.props.layerName] = tagEntry[this.tree.props.layerName] + ">" +
              (srcEntry.name ? srcEntry.name : "")
          /*srcEntry[this.tree.props.layerCode] =tagEntry[this.tree.props.layerCode] +
                  (srcEntry.code ? srcEntry.code : "");
          srcEntry[this.tree.props.parentCode] =tagEntry[this.tree.props.layerCode]*/
          srcEntry[this.tree.props.level] = tagEntry[this.tree.props.level] + 1

          hasUpdate = true
          break;
        case "before":
          srcEntry[this.tree.props.parent] = tagEntry[this.tree.props.parent] || ''
          srcEntry[this.tree.props.layerName] =
              (parentNodeLevel > 0 ? parentEntry[this.tree.props.layerName] + ">" : "") +
              (srcEntry.name ? srcEntry.name : "")
          /*srcEntry[this.tree.props.layerCode] =
                  (parentNodeLevel > 0 ? parentEntry[this.tree.props.layerCode] : "") +
                  (srcEntry.code ? srcEntry.code : "")
          srcEntry[this.tree.props.parentCode] =
                  (parentNodeLevel > 0 ? parentEntry[this.tree.props.layerCode] : "")*/
          srcEntry[this.tree.props.sort] = (tagEntry[this.tree.props.sort] || 0) - 1
          srcEntry[this.tree.props.level] = tagEntry[this.tree.props.level]
          hasUpdate = true
          break;
        case "after":
          srcEntry[this.tree.props.parent] = tagEntry[this.tree.props.parent] || ''
          srcEntry[this.tree.props.layerName] =
              (parentNodeLevel > 0 ? (dropNode.parent.data[this.tree.props.layerName] + ">") : "") +
              (srcEntry.name ? srcEntry.name : "");
          /*srcEntry[this.tree.props.layerCode] =
                  (parentNodeLevel > 0 ? parentEntry[this.tree.props.layerCode] : "") +
                  (srcEntry.code ? srcEntry.code : "");
          srcEntry[this.tree.props.parentCode] =
                  (parentNodeLevel > 0 ? parentEntry[this.tree.props.layerCode] : "")*/
          srcEntry[this.tree.props.sort] = (tagEntry[this.tree.props.sort] || 0) + 1
          srcEntry[this.tree.props.level] = tagEntry[this.tree.props.level]
          hasUpdate = true
          break;
        default:
          break
      }
      if (hasUpdate) {
        this.entitySave(srcEntry)
      }
    },
    /**tree节点选中*/
    nodeClickHandle(data, node) {
      this.tree.entry = node
      if (this.layoutMode == 'treeForm') {
        this.formMode(true, "添加", false, data)
      }
      this.$emit('choiceChange', data.id, data, node)
    },
    /**创建节点*/
    nodeCreate(data) {
      let entry = {validStatus: this.$constants.coreDict.validStatus.enum.enabled.value}
      if (!this.$utils.lodash.isEmpty(data)) {
        Object.assign(entry, data)
      }
      if (this.tree.entry && this.tree.entry.data && this.tree.entry.data.id) {
        Object.assign(entry, {parentId: this.tree.entry.data.id})
      }
      this.formMode(true, "添加", true, entry)
    },
    /**表单提交*/
    formSubmit() {
      this.$refs.dossierArchiveForm.validate((valid) => {
        if (valid) {
          this.entitySave(this.$refs.dossierArchiveForm.form.entry)
        } else {
          this.$message.error('数据校验失败,请修改后再次提交！')
        }
      })
    },
    /**搜索提交*/
    searchSubmit() {
      this.$refs.dossierArchiveSearch.validate((valid) => {
        if (valid) {
          this.searchMode(false)
          this.specifySearch()
        } else {
          this.$message.error('数据校验失败,请修改后再次查询！')
        }
      })
    },
    /**实体保存*/
    entitySave(entry) {
      dossierArchiveApi.save(entry).then(response => {
        this.responseHandle(response, "保存").then(() => {
          this.form.visible = false
          this.treeLoadRefresh();
        })
      }).catch(() => {
      })
    },
    /**实体删除*/
    entityDelete(idArr) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示',
          {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
      ).then(() => {
        dossierArchiveApi.remove({idArr: idArr}, {deleteMode: this.$constants.coreDict.deleteMode.enum.physics.value}).then(response => {
          this.responseHandle(response, "删除").then(() => {
            this.treeLoadRefresh();
          })
        })
      }).catch(() => {
      })
    },
    /**刷新Tree数据*/
    treeLoadRefresh() {
      const params = Object.assign({}, this.search.criteria)
      dossierArchiveApi.list(params).then(response => {
        this.responseHandle(response, "刷新数据").then((result) => {
          if (!this.$utils.lodash.isEmpty(result)) {
            result.sort((src, tag) => (src[this.tree.props.sort] - tag[this.tree.props.sort]))
            this.tree.nodes = this.$utils.listConvertTree(result)
          } else {
            this.tree.nodes = []
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
